package com.learning.platform.repository;

import com.learning.platform.entity.Enrollment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface EnrollmentRepository extends JpaRepository<Enrollment, Long> {
    
    /**
     * 检查用户是否已选课
     */
    boolean existsByUserIdAndCourseId(Long userId, Long courseId);
    
    /**
     * 查找用户的选课记录
     */
    Optional<Enrollment> findByUserIdAndCourseId(Long userId, Long courseId);
    
    /**
     * 获取用户的所有选课，按时间倒序
     */
    Page<Enrollment> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
    
    /**
     * 获取课程的选课人数
     */
    long countByCourseId(Long courseId);
    
    /**
     * 获取用户选课的课程ID列表
     */
    @Query("SELECT e.courseId FROM Enrollment e WHERE e.userId = :userId")
    List<Long> findCourseIdsByUserId(@Param("userId") Long userId);
    
    /**
     * 获取课程的选课用户ID列表
     */
    @Query("SELECT e.userId FROM Enrollment e WHERE e.courseId = :courseId")
    List<Long> findUserIdsByCourseId(@Param("courseId") Long courseId);
    
    /**
     * 删除课程的所有选课记录
     */
    void deleteByCourseId(Long courseId);
}



